<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { userUpdatePwdService } from '@/api/user'
import { useUserStore } from '@/stores'
import { ElMessage } from 'element-plus'
const pwdRef = ref()

// 表单数据
const pwdModel = ref({
  old_pwd: '',
  new_pwd: '',
  re_pwd: ''
})

const checkOldPassword = (rule, value, cb) => {
  if (value === pwdModel.value.old_pwd) {
    cb(new Error('新密码不能与原密码相同'))
  } else {
    cb()
  }
}

const checkNewPassword = (rule, value, cb) => {
  if (value !== pwdModel.value.new_pwd) {
    cb(new Error('两次输入的密码不一致'))
  } else {
    cb()
  }
}

const rules = {
  old_pwd: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码长度为 6-15 位非空字符',
      trigger: 'blur'
    }
  ],
  new_pwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码长度为 6-15 位非空字符',
      trigger: 'blur'
    },
    { validator: checkOldPassword, trigger: 'blur' }
  ],
  re_pwd: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码长度为 6-15 位非空字符',
      trigger: 'blur'
    },
    { validator: checkNewPassword, trigger: 'blur' }
  ]
}

const router = useRouter()
const userStore = useUserStore()
// 修改密码
const updatepwd = async () => {
  await pwdRef.value.validate()
  await userUpdatePwdService(pwdModel.value)
  ElMessage.success('修改成功，请重新登录')
  // 拦截到登录页
  userStore.removeToken()
  userStore.setUserInfo({})
  router.push('/login')
}

// 重置
const reset = () => {
  pwdRef.value.resetFields()
}
</script>
<template>
  <page-container title="重置密码">
    <el-row>
      <el-col :span="12">
        <el-form
          ref="pwdRef"
          :model="pwdModel"
          :rules="rules"
          label-width="100px"
          size="large"
        >
          <el-form-item label="原密码" prop="old_pwd">
            <el-input v-model="pwdModel.old_pwd" type="password"></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="new_pwd">
            <el-input v-model="pwdModel.new_pwd" type="password"></el-input>
          </el-form-item>
          <el-form-item label="确认新密码" prop="re_pwd">
            <el-input v-model="pwdModel.re_pwd" type="password"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="updatepwd">修改密码</el-button>
            <el-button @click="reset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </page-container>
</template>
